/**
 * Copyright &copy; 2012-2016 <a href="https://github.com/thinkgem/jeesite">JeeSite</a> All rights reserved.
 */
package com.thinkgem.jeesite.modules.sys.web;

import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.thinkgem.jeesite.common.persistence.BaseConstants;
import com.thinkgem.jeesite.common.utils.Collections3;
import com.thinkgem.jeesite.common.utils.StringUtils;
import com.thinkgem.jeesite.common.web.BaseController;
import com.thinkgem.jeesite.frame.pm.PmConstants;
import com.thinkgem.jeesite.frame.pm.entity.PmDataDictItem;
import com.thinkgem.jeesite.frame.pm.utils.PmDataDictUtils;
import com.thinkgem.jeesite.modules.sys.SysConstants;
import com.thinkgem.jeesite.modules.sys.entity.SysRole;
import com.thinkgem.jeesite.modules.sys.entity.SysUser;
import com.thinkgem.jeesite.modules.sys.service.SysRoleService;
import com.thinkgem.jeesite.modules.sys.service.SysUserService;
import com.thinkgem.jeesite.modules.sys.utils.UserUtils;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import javax.servlet.http.HttpServletResponse;
import java.util.List;
import java.util.Map;

/**
 * 角色Controller
 *
 * @author kongxiangsheng
 * @version 2013-12-05
 */
@Controller
@RequestMapping(value = "${adminPath}/sys/role")
public class SysRoleController extends BaseController {
    @Autowired
    private SysRoleService sysRoleService;
    @Autowired
    private SysUserService sysUserService;

    @RequiresPermissions("sys:sysRole:view")
    @RequestMapping(value = {"list", ""})
    public String list(SysRole role, Model model) {
        List<SysRole> list = UserUtils.getRoleList();
        model.addAttribute("list", list);
        return "modules/sys/SysRole/list";
    }

    @RequiresPermissions("sys:sysRole:view")
    @RequestMapping(value = "form")
    public String form(SysRole role, Model model) {
        if(StringUtils.isNotBlank(role.getId())) {
            role = sysRoleService.getWithMenu(role.getId());
        }else{
            role.setIsSys(BaseConstants.YES_NO_FLAG_N);
        }
        model.addAttribute("role", role);
        model.addAttribute("menuList", UserUtils.getMenuList());
        model.addAttribute("officeList", UserUtils.getOfficeList());
        return "modules/sys/SysRole/form";
    }

    @RequiresPermissions("sys:sysRole:edit")
    @RequestMapping(value = "save")
    public String save(SysRole role, Model model, RedirectAttributes redirectAttributes) {
        if (!beanValidator(model, role)) {
            return form(role, model);
        }
        if (!"true".equals(checkName(role.getOldName(), role.getName()))) {
            addMessage(model, "保存角色'" + role.getName() + "'失败, 角色名已存在");
            return form(role, model);
        }
        sysRoleService.saveRole(role);
        addMessage(redirectAttributes, "保存角色'" + role.getName() + "'成功");
        return "redirect:" + adminPath + "/sys/role/?repage";
    }

    @RequiresPermissions("sys:sysRole:edit")
    @RequestMapping(value = "delete")
    public String delete(SysRole role, RedirectAttributes redirectAttributes) {
        sysRoleService.deleteRole(role);
        addMessage(redirectAttributes, "删除角色成功");
        return "redirect:" + adminPath + "/sys/role/?repage";
    }

    /**
     * 角色分配页面
     *
     * @param role
     * @param model
     * @return
     */
    @RequiresPermissions("sys:sysRole:edit")
    @RequestMapping(value = "assign")
    public String assign(SysRole role, Model model) {
        List<SysUser> userList = sysUserService.findUserByRoleId(role.getId());
        model.addAttribute("userList", userList);
        return "modules/sys/SysRole/assign";
    }

    /**
     * 角色分配 -- 打开角色分配对话框
     *
     * @param role
     * @param model
     * @return
     */
    @RequiresPermissions("sys:sysRole:view")
    @RequestMapping(value = "usertorole")
    public String selectUserToRole(SysRole role, Model model) {
        List<SysUser> userList = sysUserService.findUserByRoleId(role.getId());
        model.addAttribute("role", role);
        model.addAttribute("userList", userList);
        model.addAttribute("selectIds", Collections3.extractToString(userList, "name", ","));
        model.addAttribute("officeList", UserUtils.getOfficeList());
        return "modules/sys/SysRole/selectUserToRole";
    }

    /**
     * 角色分配 -- 根据部门编号获取用户列表
     *
     * @param officeId
     * @param response
     * @return
     */
    @RequiresPermissions("sys:sysRole:view")
    @ResponseBody
    @RequestMapping(value = "users")
    public List<Map<String, Object>> users(String officeId, HttpServletResponse response) {
        List<Map<String, Object>> mapList = Lists.newArrayList();
        List<SysUser> userList = sysUserService.findUserByOfficeId(officeId);
        for (SysUser e : userList) {
            Map<String, Object> map = Maps.newHashMap();
            map.put("id", e.getId());
            map.put("pId", 0);
            map.put("name", e.getName());
            mapList.add(map);
        }
        return mapList;
    }

    /**
     * 角色分配 -- 从角色中移除用户
     *
     * @param userId
     * @param roleId
     * @param redirectAttributes
     * @return
     */
    @RequiresPermissions("sys:sysRole:edit")
    @RequestMapping(value = "removeUserRole")
    public String removeUserRole(String userId, String roleId, RedirectAttributes redirectAttributes) {
        SysRole role = sysRoleService.getById(roleId);
        SysUser user = UserUtils.get(userId);
        if (UserUtils.getUser().getId().equals(userId)) {
            addMessage(redirectAttributes, "无法从角色【" + role.getName() + "】中移除用户【" + user.getName() + "】自己！");
        } else {
            if (user.getRoleList().size() <= 1) {
                addMessage(redirectAttributes, "用户【" + user.getName() + "】从角色【" + role.getName() + "】中移除失败！这已经是该用户的唯一角色，不能移除。");
            } else {
                sysRoleService.deleteUserRole(userId, roleId);
                addMessage(redirectAttributes, "用户【" + user.getName() + "】从角色【" + role.getName() + "】中移除成功！");
            }
        }
        return "redirect:" + adminPath + "/sys/role/assign?id=" + role.getId();
    }

    /**
     * 角色分配
     *
     * @param role
     * @param idsArr
     * @param redirectAttributes
     * @return
     */
    @RequiresPermissions("sys:sysRole:edit")
    @RequestMapping(value = "assignrole")
    public String assignRole(SysRole role, String[] idsArr, RedirectAttributes redirectAttributes) {
        StringBuilder msg = new StringBuilder();
        int newNum = 0;
        for (int i = 0; i < idsArr.length; i++) {
            SysUser user = UserUtils.get(idsArr[i]);
            sysRoleService.insertUserRole(user.getId(),role.getId());
            if (null != user) {
                msg.append("<br/>新增用户【" + user.getName() + "】到角色【" + role.getName() + "】！");
                newNum++;
            }
        }
        addMessage(redirectAttributes, "已成功分配 " + newNum + " 个用户" + msg);
        return "redirect:" + adminPath + "/sys/role/assign?id=" + role.getId();
    }

    /**
     * 验证角色名是否有效
     *
     * @param oldName
     * @param name
     * @return
     */
    @RequiresPermissions("user")
    @ResponseBody
    @RequestMapping(value = "checkName")
    public String checkName(String oldName, String name) {
        if (name != null && name.equals(oldName)) {
            return "true";
        } else if (name != null && sysRoleService.getByName(name) == null) {
            return "true";
        }
        return "false";
    }
    /**
     * 指定用户类型的用户信息查询
     *
     * @param sysRole
     * @param model
     * @return
     */
    @RequiresPermissions("sys:sysRole:view")
    @RequestMapping(value = {"busiList"})
    public String busiList(SysRole sysRole, Model model) {
        List<SysRole> list = UserUtils.getRoleList();
        model.addAttribute("list", list);
        return "modules/sys/SysRole/busiList";
    }

    /**
     * 指定用户类型的用户信息查看
     *
     * @param sysRole
     * @param model
     * @return
     */
    @RequiresPermissions("sys:sysRole:view")
    @RequestMapping(value = "busiForm")
    public String busiForm(SysRole sysRole, Model model) {
        if(StringUtils.isNotBlank(sysRole.getId())) {
            sysRole = sysRoleService.getWithMenu(sysRole.getId());
        }
        model.addAttribute("role", sysRole);
        model.addAttribute("menuList", UserUtils.getMenuList());
        model.addAttribute("officeList", UserUtils.getOfficeList());
        return "modules/sys/SysRole/busiForm";
    }

    @RequiresPermissions("sys:sysRole:edit")
    @RequestMapping(value = "busiSave")
    public String busiSave(SysRole role, Model model, RedirectAttributes redirectAttributes) {
        if (!beanValidator(model, role)) {
            return form(role, model);
        }
        if (!"true".equals(checkName(role.getOldName(), role.getName()))) {
            addMessage(model, "保存岗位'" + role.getName() + "'失败, 岗位名称已存在");
            return form(role, model);
        }
        sysRoleService.saveRole(role);
        addMessage(redirectAttributes, "保存岗位'" + role.getName() + "'成功");
        return "redirect:" + adminPath + "/sys/role/busiList?repage";
    }

    @RequiresPermissions("sys:sysRole:edit")
    @RequestMapping(value = "busiDelete")
    public String busiDelete(SysRole role, RedirectAttributes redirectAttributes) {
        sysRoleService.deleteRole(role);
        addMessage(redirectAttributes, "删除岗位成功");
        return "redirect:" + adminPath + "/sys/role/busiList?repage";
    }

}
